package cn.heapstack.jpa.entityrelationships.main;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.UUID;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import cn.heapstack.jpa.entityrelationships.domain.Address;
import cn.heapstack.jpa.entityrelationships.domain.CreditCard;
import cn.heapstack.jpa.entityrelationships.domain.Customer;
import cn.heapstack.jpa.entityrelationships.domain.Phone;

public class MainForOneToMany {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("EntityRelationships");
		EntityManager em = factory.createEntityManager();

		em.getTransaction().begin();

		String lastName = UUID.randomUUID().toString();

		Customer customer = new Customer();
		Address address = new Address();
		CreditCard creditCard = new CreditCard();
		Collection<Phone> phoneNumbers = new ArrayList<Phone>();

		address.setCity("city");
		address.setState("state");
		address.setStreet("street");

		creditCard.setExpiration(new Date());
		creditCard.setName("name");
		creditCard.setNumber("number");
		creditCard.setOrgrnization("orgrnization");
		
		Phone phone = new Phone("13745678901",1);
		phoneNumbers.add(phone);
		phoneNumbers.add(new Phone("+86 13 22089576",2));
		phoneNumbers.add(new Phone("+86 13 22089500",2));
		
		customer.setFirstName("firstName");
		customer.setLastName("lastName:" + lastName);
		customer.setAddress(address);
		customer.setCreditCard(creditCard);
		creditCard.setCustomer(customer);
		customer.setPhoneNumbers(phoneNumbers);

		em.persist(customer);

		//注意：这里想要删除Phone的话，必须从集合和数据库中都删掉，如下
		phoneNumbers.remove(phone);
		//看上去下面两个方法都能达到效果
		//em.merge(customer);
		em.remove(phone);

		em.getTransaction().commit();
		em.close();
		factory.close();
	}

}
